﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using StockSystem.StockSystem.InStocks.Dtos;
using StockSystem.StockSystem.Stockings;
using StockSystem.StockSystem.InStocks;
using Microsoft.Extensions.Logging;
using Abp.Timing;

namespace StockSystem.StockSystem.InStocks
{
    public class InStockSummaryAppService : StockSystemAppServiceBase, IInStockSummaryAppService
    {

        private readonly IRepository<InStockSummary> _inStockSummary;
        private readonly IRepository<Stocking> _stockingRepository;
        private readonly IRepository<InStockDetail> _inStockDetail;
        private readonly IRepository<Goods.Goods> _goods;

        public InStockSummaryAppService(IRepository<InStockSummary> inStockSummary, 
        IRepository<Stocking> stockingRepository,
        IRepository<InStockDetail> inStockDetail,
        IRepository<StockSystem.Goods.Goods> goods)
        {
            this._inStockSummary = inStockSummary;
            this._stockingRepository = stockingRepository;
            this._inStockDetail = inStockDetail;
            this._goods = goods;
        }
        //执行入库业务(传id则是修改入库单，不传id则是新增入库单)
        public async Task DoInStockAsync(CreateOrUpdateInStockInput input)
        {
            var InStockSummaryEditDto = input.InStockSummaryEditDto;
            //根据是否传入id属性（InStockSummary抬头的id）来判断是修改还是更新
            if(InStockSummaryEditDto.Id != null){
                //修改这个入库订单
                Decimal totalAmount = 0;//订单总金额
                //计算每条小条目的总金额
                InStockSummaryEditDto.InStockDetails.ForEach(e => {
                    e.InStockSumPrice = e.InStockAmount * e.InStockPrice;
                    totalAmount += e.InStockSumPrice;//计算订单总金额
                });

                InStockSummaryEditDto.TotalAmount = totalAmount;

                //把InStockSummaryEditDto转换为InStockSummary对象
                InStockSummary inStockSummary = InStockSummaryEditDto.MapTo<InStockSummary>();
                List<InStockDetail> list = (List<InStockDetail>)inStockSummary.InStockDetails;                
                
                //把旧记录的库存都删除
                var inStockDetails = await _inStockDetail.GetAll().Where(e => e.InStockSummaryId == inStockSummary.Id).ToListAsync();
                inStockDetails.ForEach(e => {
                    var entity = _stockingRepository.GetAll().Where(x=>x.GoodsId==e.GoodsId).FirstOrDefault();
                    var amount = entity.StockingNumber - e.InStockAmount;//计算新库存值
                    if (amount < 0)
                        amount = 0;
                    entity.StockingNumber = amount;
                    _stockingRepository.Update(entity);
                });
                await _inStockDetail.DeleteAsync(e=>e.InStockSummaryId==inStockSummary.Id);//把旧记录删除
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].Goods = await _goods.GetAsync(list[i].GoodsId);
                    list[i].Id = 0;//把id设置为null
                    await _inStockDetail.InsertAsync(list[i]);//重新插入新记录
                }
                inStockSummary.OperatingTime = Clock.Now;
                //更新数据
                await _inStockSummary.UpdateAsync(inStockSummary);
                
                   
                //修改库存表-判断某条货物是否在库存表中存在？存在则Update，不存在则insert
                InStockSummaryEditDto.InStockDetails.ForEach(e => {
                    var res = _stockingRepository.GetAll().FirstOrDefault(x=>x.GoodsId==e.GoodsId);
                    if (res == null)
                    {
                        //insert（当前入库数量）
                        var entity = new Stocking {
                            StockingNumber = e.InStockAmount,
                            GoodsId = e.GoodsId
                        };
                        _stockingRepository.Insert(entity);
                    }
                    else
                    {
                        //update(原本数量+当前入库数量)
                        res.StockingNumber += e.InStockAmount;
                        _stockingRepository.Update(res);
                    }
                });
            }else{
                //新增入库订单
                //判断入库单号是否已经存在
                var o1 = _inStockSummary.GetAll().FirstOrDefault(x => x.InStockCode == InStockSummaryEditDto.InStockCode);
                if(o1 != null)
                {
                    throw new UserFriendlyException("您输入的单号已经存在，请重新输入！");
                }

                Decimal totalAmount = 0;//订单总金额
                //计算每条小条目的总金额
                InStockSummaryEditDto.InStockDetails.ForEach(e => {
                    e.InStockSumPrice = e.InStockAmount * e.InStockPrice;
                    totalAmount += e.InStockSumPrice;//计算订单总金额
                });

                InStockSummaryEditDto.TotalAmount = totalAmount;

                //把InStockSummaryEditDto转换为InStockSummary对象
                InStockSummary inStockSummary = InStockSummaryEditDto.MapTo<InStockSummary>();
                //插入数据
                inStockSummary.OperatingTime = Clock.Now;
                await _inStockSummary.InsertAsync(inStockSummary);

                //修改库存表-判断某条货物是否在库存表中存在？存在则Update，不存在则insert
                InStockSummaryEditDto.InStockDetails.ForEach(e => {
                    var res = _stockingRepository.GetAll().FirstOrDefault(x=>x.GoodsId==e.GoodsId);
                    if (res == null)
                    {
                        //insert（当前入库数量）
                        var entity = new Stocking {
                            StockingNumber = e.InStockAmount,
                            GoodsId = e.GoodsId
                        };
                        _stockingRepository.Insert(entity);
                    }
                    else
                    {
                        //update(原本数量+当前入库数量)
                        res.StockingNumber += e.InStockAmount;
                        _stockingRepository.Update(res);
                    }
                });
    
            }
            
            
        }

        // 查询已入库的订单
        public async Task<PagedResultDto<InStockSummaryListDto>> GetPagedInStockSummaryAsync(GetInStockSummaryInput input)
        {
            var query = _inStockSummary.GetAllIncluding(x=>x.Supplier);            
            var inStockSummariesCount = await query.CountAsync();
            var inStockSummaries = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
            var dtos = inStockSummaries.MapTo<List<InStockSummaryListDto>>();
            dtos.ForEach(x=> {
                if(x.Supplier != null)
                {
                    x.SupplierName = x.Supplier.SupplierName;
                }
            });
            return new PagedResultDto<InStockSummaryListDto>(inStockSummariesCount, dtos);
            
        }

        public async Task<InStockSummaryListDto> GetInstockSummaryByIdAsync(NullableIdDto<int> input){             
            var entity = await _inStockSummary.GetAll()
                .Include(x=>x.InStockDetails)
                .ThenInclude(x => x.Goods)//查询Summary中的Details,同时把Details中的Goods查出来                
                .Include(x=>x.Supplier)                
                .Where(x=>x.Id==input.Id.Value).FirstOrDefaultAsync();             
            if(entity==null){                
                throw new UserFriendlyException("找不到这条入库订单！");               
            }
            var dto = entity.MapTo<InStockSummaryListDto>();
            return dto;
        }
    }
}
